<?php
// 使用 cURL 获取地理位置信息
function getGeoInfo($ip) {
    $url = 'https://qifu-api.baidubce.com/ip/geo/v1/district?ip=' . $ip;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过SSL验证

    $response = curl_exec($ch);
    if (curl_errno($ch)) {
        return null;
    }
    curl_close($ch);

    return $response;
}

// 数据库连接配置
$servername = "127.0.0.1";
$username = "test_ynhbg_com";
$password = "z2wR5fXj6yY5aZM9";
$dbname = "test_ynhbg_com";

// 创建数据库连接
$conn = new mysqli($servername, $username, $password, $dbname);

// 检查连接
if ($conn->connect_error) {
    die("连接失败: " . $conn->connect_error);
}

// 检查是否有POST请求
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // 检查是否传递了IP地址和URL
    if (isset($_POST['ip']) && isset($_POST['url'])) {
        $ip = $_POST['ip'];
        $url = $_POST['url'];
        $qudao = $_POST['qudao']>=1?$_POST['qudao']:'0';
        
        // 使用百度的接口获取地理位置信息
        $geoData = getGeoInfo($ip);
        $geoInfo = json_decode($geoData, true);
        
        // 检查是否成功获取到地理位置信息
        if ($geoInfo && isset($geoInfo['data'])) {
            $location = $geoInfo['data']['country'] . ', ' . $geoInfo['data']['province'] . ', ' . $geoInfo['data']['city'];
        } else {
            $location = 'Unknown location';
        }
        $checktime=time()-300;
        $logchecksql="SELECT * FROM ay_visit_log where ip='".$ip."' and url='".$url."' and addtime>='".$checktime."'";
        $logcheckfind=mysqli_query($conn,$logchecksql);
        // 记录当前时间
        echo $logchecksql;
        if ($logcheckfind and mysqli_num_rows($logcheckfind)>=1) 
        {
            $logcheckshow=mysqli_fetch_array($logcheckfind);
            $logid=$logcheckshow['id'];
            mysqli_query($conn,"UPDATE ay_visit_log SET visittime=visittime+1 where id='".$logid."'");
        }
        else {
            $sql = "INSERT INTO ay_visit_log (addtime, ip, city, url,visittime,status) VALUES ('".time()."','".$ip."','".$location."','".$url."','0','".$qudao."')";
            if (mysqli_query($conn, $sql)) {
                echo 'IP地址、地理位置信息和URL已成功记录';
            } else {
                echo '记录失败: ' . mysqli_error($conn);
            }
        }
        
        // 插入数据到数据库
        
    } else {
        echo '未提供IP地址或URL';
    }
} else {
    echo '无效的请求方法';
}

$conn->close();
?>
